package com.lxx.bigevent.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxx.bigevent.mapper.ArticleMapper;
import com.lxx.bigevent.pojo.Article;
import com.lxx.bigevent.pojo.PageBean;
import com.lxx.bigevent.service.ArticleService;
import com.lxx.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        // 补充属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        article.setCreateUser(id);

        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");

        // 1.查询前设置分页参数，参数一：页数，从1开始；参数二：每天条数
        PageHelper.startPage(pageNum, pageSize);
        // 2.正常查询
        List<Article> list = articleMapper.list(categoryId, state, id);
        // 3.创建页面对象，将查询结果传入构造方法
        PageInfo<Article> pageInfo = new PageInfo<>(list);

        PageBean<Article> pageBean = new PageBean<>();
        pageBean.setTotal(pageInfo.getTotal());
        pageBean.setItems(pageInfo.getList());
        return pageBean;
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

    @Override
    public Article detail(Integer id) {
        return articleMapper.findById(id);
    }

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }
}
